#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Zhangcl
import pika
import os
import time
import socket

def get_ip():
    '''
    获取服务端的ip地址，进行关键字绑定
    :return:
    '''
    try:
        csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        csock.connect(('8.8.8.8', 80))
        (addr, port) = csock.getsockname()
        csock.close()
        return addr
    except socket.error:
        return "127.0.0.1"

connection = pika.BlockingConnection(pika.ConnectionParameters(
    host='localhost'))

channel = connection.channel()
channel.exchange_declare('direct_logs','direct') #定义和客户端一样的广播类型

result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue

channel.queue_bind(exchange='direct_logs',
                       queue=queue_name,
                        routing_key=get_ip())



def run(n):
    '''
    执行接收到的命令，并返回
    :param n:
    :return:
    '''
    time.sleep(10)
    a =os.popen(n.decode()).read()
    return a


def on_request(ch, method, props, body):
    n = body

    print(" [.] run(%s)" % n)
    response = run(n) #调用执行命令函数

    ch.basic_publish(exchange='',  #将结果返回给客户端
                     routing_key=props.reply_to,
                     properties=pika.BasicProperties(correlation_id= \
                                                         props.correlation_id),
                     body=response)
    ch.basic_ack(delivery_tag=method.delivery_tag)


channel.basic_consume(on_request, queue=queue_name)#接收

print(" [x] Awaiting RPC requests")
channel.start_consuming()
